<template>
    <h-section :title="disabled ? '需求分发信息' : '需求分发'" collapse>
        <!-- 1.阶段是分发之后的不可编辑 2.子需求没有拆分功能所以不可编辑 -->
        <div v-if="disabled || detail.relateRequest > 0">
            <!-- 子需求列表 -->
            <a-table rowKey="uuid" size="small" :columns="taskTableColumns" :data-source="form.sonRequestInfos" :pagination="false" :expandIcon="handleExpandIcon">
                <template #requestName="{ record }">
                    <flexbox v-if="detail.relateRequest > 0">
                        <a-tooltip :title="record.requestName">
                            <div style="flex: 1; cursor: pointer" v-fitText>{{ record.requestName }}</div>
                        </a-tooltip>
                        <div v-if="record.id === detail.id">
                            <a-tag color="processing" style="margin-left: 8px">当前需求</a-tag>
                        </div>
                    </flexbox>
                    <a-tooltip :title="record.requestName" v-else>
                        <div style="cursor: pointer" v-fitText>{{ record.requestName }}</div>
                    </a-tooltip>
                </template>
                <template #system="{ record }">
                    {{ $filters.valToNameFilter('fromSystem', record.requestSystem) }}
                </template>
                <template #action="{ record }">
                    <a @click="jumpTo(record.id)" v-if="record.id">详情</a>
                </template>
                <!-- 产品需求 -->
                <template #expandedRowRender="{ record }">
                    <a-table rowKey="id" :columns="productTableColumns" :data-source="record.pmpProductRequires" :pagination="false">
                        <template #requireType="{ record }">
                            <h-product-type :type="$filters.valToNameFilter('requireType', record.requireType)" />
                        </template>
                        <template #level="{ record }">
                            <h-level :level="record.level" v-if="record.level" />
                        </template>
                        <template #stage="{ record }"> {{ $filters.valToNameFilter('stage', record.stage) }} </template>
                        <template #status="{ record }">
                            <flexbox>
                                <a-badge status="success" :text="$filters.valToNameFilter('status', record.status)" />
                            </flexbox>
                        </template>
                    </a-table>
                </template>
            </a-table>
        </div>
        <div v-else>
            <a-button block type="dashed" style="margin: 0 0 8px 0" @click="handleCreate">
                <PlusOutlined />
                <span>添加</span>
            </a-button>
            <custom-table ref="ruleTableRef" rowKey="uuid" size="small" :rules="taskTableRules" :columns="taskTableColumns" :data-source="form.sonRequestInfos" :pagination="false" v-if="detail.status === '1'">
                <template #system="{ record, index }">
                    <h-search-select-cell :default-value="$filters.valToNameFilter('fromSystem', record.requestSystem)" type="allSystem" label="system" @success="handleSelectChange($event, 'requireSystem', index)" style="width: 100%" />
                </template>
                <template #requestName="{ record }">
                    <a-input v-model:value="record.requestName" />
                </template>
                <template #agentUserName="{ record, index }">
                    <h-search-select-cell :default-value="record.agentUserName" type="systemManager" label="empName" :searchQuery="{ catalogCode: record.pmpSystemManager.catalogCode }" @success="handleSelectChange($event, 'systemManager', index)" style="width: 100%" />
                </template>
                <template #action="{ record, index }">
                    <a @click="handleDelete(record, index)">删除</a>
                </template>
            </custom-table>
            <custom-table ref="ruleTableRef" rowKey="uuid" size="small" :rules="taskTableRules" :columns="taskTableColumns" :data-source="form.sonRequestInfos" :pagination="false" v-else>
                <template #system="{ record, index }">
                    <h-search-select-cell :default-value="$filters.valToNameFilter('fromSystem', record.requestSystem)" type="allSystem" label="system" @success="handleSelectChange($event, 'requireSystem', index)" style="min-width: 200px; width: 100%" v-if="record.stage === '4'" />
                    <div v-else>
                        <span v-if="record.id && detail.responsibleEmpId !== record.responsibleEmpId">
                            {{ $filters.valToNameFilter('fromSystem', record.requestSystem) }}
                        </span>
                        <h-search-select-cell :default-value="$filters.valToNameFilter('fromSystem', record.requestSystem)" type="allSystem" label="system" @success="handleSelectChange($event, 'requireSystem', index)" style="min-width: 200px; width: 100%" v-else />
                    </div>
                </template>
                <template #requestName="{ record }">
                    <a-input v-model:value="record.requestName" v-if="record.stage === '4'" />
                    <div v-else>
                        <a-tooltip :title="record.requestName" v-if="record.id && detail.responsibleEmpId !== record.responsibleEmpId">
                            <div class="cursor-pointer" v-fitText>
                                {{ record.requestName }}
                            </div>
                        </a-tooltip>
                        <a-input v-model:value="record.requestName" v-else />
                    </div>
                </template>
                <template #agentUserName="{ record, index }">
                    <h-search-select-cell :default-value="record.agentUserName" type="systemManager" label="empName" :searchQuery="{ catalogCode: record.pmpSystemManager.catalogCode }" @success="handleSelectChange($event, 'systemManager', index)" style="min-width: 200px; width: 100%" v-if="record.stage === '4'" />
                    <div v-else>
                        <span v-if="record.id && detail.responsibleEmpId !== record.responsibleEmpId">
                            {{ record.agentUserName }}
                        </span>
                        <h-search-select-cell :default-value="record.agentUserName" type="systemManager" label="empName" :searchQuery="{ catalogCode: record.pmpSystemManager.catalogCode }" @success="handleSelectChange($event, 'systemManager', index)" style="min-width: 200px; width: 100%" v-else />
                    </div>
                </template>
                <template #action="{ record, index }">
                    <span v-if="record.id && +record.stage > 4">
                        <span v-if="detail.responsibleEmpId !== record.responsibleEmpId">
                            <a @click="handleDistribute(2, record)">撤回分发</a>
                            <a-divider type="vertical" />
                            <a @click="jumpTo(record.id)">详情</a>
                        </span>
                        <span v-else>
                            <a @click="handleDistribute(0, record, index)">保存</a>
                            <a-divider type="vertical" />
                            <a @click="handleDistribute(1, record, index)">分发</a>
                            <a-divider type="vertical" />
                            <a @click="handleDelete(record, index)">删除</a>
                        </span>
                    </span>
                    <span v-else>
                        <a @click="handleDistribute(0, record, index)">保存</a>
                        <a-divider type="vertical" />
                        <a @click="handleDistribute(1, record, index)">分发</a>
                        <a-divider type="vertical" />
                        <a @click="handleDelete(record, index)">删除</a>
                    </span>
                </template>
            </custom-table>
            <flexbox justify="flex-end" class="btn-group" v-if="form.sonRequestInfos.length && detail.status === '1'">
                <a-button @click="handleSave('否')">保存</a-button>
                <a-button type="primary" @click="handleSave('是')">分发需求</a-button>
            </flexbox>
        </div>
    </h-section>
</template>

<script lang="ts">
import api from '@/api';
import { message } from 'ant-design-vue';
import { expandIcon } from '@/utils/renderCustomFn.tsx';
import { PlusOutlined } from '@ant-design/icons-vue';
import { useRouter } from 'vue-router';
import store from '@/store';
import { HLevel, HProductType, HSearchSelectCell, CustomTable } from '@/components';
import { defineComponent, ref, unref, watch } from 'vue';
import uuid from 'node-uuid';
interface FormState {
    handOut: string;
    sonRequestInfos: Array<any>;
    requestSystem: Nullable<string>;
}
export default defineComponent({
    name: 'RequireDistributation',
    components: {
        HLevel,
        HProductType,
        HSearchSelectCell,
        CustomTable,
        PlusOutlined
    },
    props: {
        detail: { type: Object, default: () => ({}) },
        disabled: { type: Boolean, default: false }
    },
    emits: ['success', 'save'],
    setup(props, { emit }) {
        const router = useRouter();
        const form = ref<FormState>({
            handOut: '',
            sonRequestInfos: [],
            requestSystem: null
        });
        const createStoryRef = ref<any>();
        const ruleTableRef = ref<any>();
        const checkIsRepeat = () => {
            let nameArr: any[];
            nameArr = unref(form).sonRequestInfos.map((item) => item.requestName.trim());
            const newNameArr = Array.from(new Set([...nameArr]));
            return newNameArr.length !== nameArr.length;
        };
        const validateRepeat = (rule: any, value: any) => {
            if (value) {
                return checkIsRepeat() ? Promise.reject('子需求名称重复') : Promise.resolve();
            } else {
                return Promise.reject('子需求名称不能为空');
            }
        };
        const taskTableRules = {
            requestName: [
                { required: true, message: '子需求名称不能为空' },
                {
                    validator: validateRepeat,
                    message: '子需求名称重复'
                }
            ],
            agentUserName: [{ required: true, message: '产品经理不能为空' }]
        };
        const taskTableColumns = [
            {
                title: '系统',
                dataIndex: 'system',
                key: 'system',
                slots: { customRender: 'system' }
            },
            {
                title: '子需求名称',
                dataIndex: 'requestName',
                key: 'requestName',
                align: 'center',
                ellipsis: true,
                slots: { customRender: 'requestName' }
            },
            {
                title: '负责人',
                dataIndex: 'agentUserName',
                key: 'agentUserName',
                align: 'center',
                slots: { customRender: 'agentUserName' }
            },
            {
                title: '操作',
                dataIndex: 'action',
                key: 'action',
                slots: { customRender: 'action' }
            }
        ];
        // 表格验证信息
        const tableValidateMsgs: any = [];
        const productTableColumns = [
            {
                title: '需求名称',
                dataIndex: 'requireName',
                ellipsis: true
            },
            {
                title: '需求类型',
                dataIndex: 'requireType',
                slots: { customRender: 'requireType' }
            },
            {
                title: '优先级',
                dataIndex: 'level',
                slots: { customRender: 'level' }
            },
            {
                title: '阶段',
                dataIndex: 'stage',
                slots: { customRender: 'stage' }
            },
            {
                title: '状态',
                dataIndex: 'status',
                slots: { customRender: 'status' }
            }
        ];
        const handleCreate = () => {
            const dicOptions: any = store.getters.dicOptions;
            const res = dicOptions.fromSystem.find((item) => item.code === props.detail.requestSystem);
            const system = res ? res.systemName : dicOptions.fromSystem[0].systemName;
            const item = {
                requestSystem: res ? res.code : dicOptions.fromSystem[0].code,
                system,
                requestName: `【${system}】${props.detail.requestName}`,
                agentUserName: '',
                agentUser: '',
                pmpSystemManager: {
                    catalogCode: props.detail.pmpProductDetailDTO.catalogCode
                },
                uuid: uuid.v4()
            };
            form.value.sonRequestInfos = [...unref(form).sonRequestInfos, item];
        };
        const selectSystemChange = (target, index: number) => {
            const requestName = form.value.sonRequestInfos[index].requestName;
            const systemNameIndex = requestName.indexOf('】');
            form.value.sonRequestInfos[index] = {
                ...unref(form).sonRequestInfos[index],
                requestSystem: target.systemId.toString(),
                system: target.system,
                requestName: `【${target.system}】${requestName.slice(systemNameIndex + 1)}`,
                pmpSystemManager: {
                    ...target,
                    catalogCode: target.catalogCode
                }
            };
        };
        // 有id说明已经保存过，调用接口，没id说明没保存直接手动删除
        const handleDelete = async ({ id }, index: number) => {
            if (unref(form).sonRequestInfos.length === 1) {
                message.error('当前是最后一条无法删除');
                return;
            }
            if (id) {
                const query = {
                    id
                };
                const { success, errorMsg } = await api.pmpRequestInfoModel.delete(query);
                if (success) {
                    message.success('删除成功');
                    form.value.sonRequestInfos = unref(form).sonRequestInfos.filter((item) => item.id !== id);
                } else {
                    message.error(errorMsg);
                }
            } else {
                form.value.sonRequestInfos.splice(index, 1);
            }
        };
        const validate = () => {
            return unref(ruleTableRef) ? unref(ruleTableRef).validate() : Promise.resolve(true);
        };

        // 动态控制展开图标
        const handleExpandIcon = (props) => {
            // 从外部引入，是因为内部不支持jsx
            return expandIcon(props, 'pmpProductRequires');
        };
        // 通用选择回调
        const handleSelectChange = (val, field: string, index: number) => {
            if (field === 'systemManager') {
                form.value.sonRequestInfos[index] = {
                    ...unref(form).sonRequestInfos[index],
                    agentUserName: val.empName,
                    agentUser: val.empId
                };
            }
            if (field === 'requireSystem') {
                selectSystemChange(val, index);
            }
        };
        // 保存
        const handleSave = (handOut: string) => {
            const { sonRequestInfos } = unref(form);
            form.value.handOut = handOut;
            if (handOut === '是' && sonRequestInfos && sonRequestInfos.length) {
                const allSystem = sonRequestInfos.map((item) => item.requestSystem);
                form.value.requestSystem = Array.from(new Set([...allSystem])).join(',');
            }
            emit('save');
        };
        // 分发
        const handleDistribute = async (type: number, record, index?: number) => {
            if (type === 1) {
                if (props.detail.responsibleEmpId === record.agentUser) {
                    message.error('不能分发给当前负责人');
                    return;
                }
            }
            const query = {
                type: type.toString(),
                requestInfo: record
            };
            let res = true;
            // 需要交验
            if ([0, 1].includes(type)) {
                res = await unref(ruleTableRef).validateRow(record, index);
            }
            // 新建
            if ([0, 1].includes(type)) {
                query.requestInfo.relateRequest = props.detail.id;
            }
            if (res) {
                const { success, errorMsg } = await api.pmpRequestInfoModel.updateSplit(query);
                if (success) {
                    message.success('操作成功');
                    emit('success');
                } else {
                    message.error(errorMsg);
                }
            }
        };
        const jumpTo = (id: number) => {
            router.push({
                path: '/taskRequire/taskDetail',
                query: {
                    id,
                    type: 0
                }
            });
        };
        const init = () => {
            if (props.detail.sonRequestInfos && props.detail.sonRequestInfos.length) {
                form.value.sonRequestInfos = props.detail.sonRequestInfos.map((item) => ({
                    ...item,
                    system: item.pmpSystemManager.systemName,
                    uuid: uuid.v4()
                }));
            }
            form.value.requestSystem = props.detail.requestSystem;
        };
        init();
        watch(() => props.detail, init, {
            deep: true
        });
        return {
            createStoryRef,
            ruleTableRef,
            form,
            taskTableRules,
            taskTableColumns,
            tableValidateMsgs,
            productTableColumns,
            handleDistribute,
            handleSave,
            jumpTo,
            validate,
            handleExpandIcon,
            handleSelectChange,
            handleCreate,
            handleDelete
        };
    }
});
</script>
<style lang="less" scoped>
button {
    margin-left: 8px;
}
.btn-group {
    margin-top: 24px;
}
.nosplit-cont {
    .ant-select {
        width: 280px;
    }
    .tip {
        font-size: 12px;
        color: #b3b6bb;
        margin-left: 8px;
    }
}
</style>